﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Configuration;

using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.BusinessLogic;

using Ivy.Common.Framework.GeneralUtility;

using DasIdeen.ViewEntity;


namespace DasIdeen.UserControls
{
    public partial class LoginControl : System.Web.UI.UserControl
    {
        #region  Variable & constant
        const Int32 constUserKey = 1;
        const string constCultureInfo = "CultureInfo";
        #endregion  Variable & constant

        #region Constructor & Destructor
        #endregion Constructor & Destructor

        #region Properties
        #endregion Properties

        #region Public Methods
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitializeScreen();
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(this.txtUserID.Text))
                {
                    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    if (lUserRegistrationBus.Login(this.txtUserID.Text, this.txtPassword.Text))
                    {
                        //this.lblLoginFailure.Visible = false;
                        InitializeAuthenticatedUserSession();
                    }
                    else
                    {
                        //Page.ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<Script language ='javascript'> alert("pravesh")
                        // </Script>;
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "{some text for type}", "alert('Login Failure - Usename and password are not matching'); ", true);
                        //this.lblLoginFailure.Visible = true;
                    }
                }
                InitializeScreen();
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            try
            {
                Session.Clear();
                Session.Abandon();
                Response.Redirect("~/Default.aspx");
                InitializeScreen();
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void lnkSystemAdmin_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/AdminHomePage.aspx");
        }
        #endregion Events

        #region Private Methods
        private void CheckUserAutherization()
        {
        }

        private void ClearScreen()
        {
            //if any
        }

        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    this.lblWelcomeMessage.Text = "Welcome " + tempUserSession.CurrentUser.UserFirstName + " " + tempUserSession.CurrentUser.UserLastName;

                    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    if (lUserRegistrationBus.IsUserHavingAdministratorAuthorization(tempUserSession.CurrentUser.UserKey))
                    {
                        this.lnkSystemAdmin.Visible = true;
                    }
                    this.DivLoginSection.Visible = false;
                    this.DivLogoutDetails.Visible = true;

                    if (!tempUserSession.CurrentUser.UserIsVerified)
                    {
                        if (this.Page.Title != "UserVerification")
                        {
                            if (tempUserSession.IsUserVerificationRequired == true)
                            {
                                Response.Redirect("~/Pages/UserVerification.aspx", true);
                            }
                        }
                    }
                }
                else
                {
                    this.DivLoginSection.Visible = true;
                    this.DivLogoutDetails.Visible = false;
                }
            }
            else
            {
                this.DivLoginSection.Visible = true;
                this.DivLogoutDetails.Visible = false;
            }
        }

        private void FillLoadLookUpData()
        {
            //if any
        }

        private void TranslateEntityToUIControls()
        {
            //if any. It is mostly used if screen is having any CRUD operation feature
        }

        private void TranslateUIControlsToEntity()
        {
            //if any. It is mostly used if screen is having any CRUD operation feature
        }

        private void InitializeAuthenticatedUserSession()
        {
            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
            User lUser = new User();
            UserContext tempUserSession;
            lUser = lUserRegistrationBus.GetUserByLoginID(this.txtUserID.Text.Trim());

            if (Session["UserContext"] != null)
            {
                 tempUserSession = (UserContext)Session["UserContext"];
            }
            else
            {
                 tempUserSession = new UserContext();
            }
            tempUserSession.UserSessionID = HttpContext.Current.Session.SessionID;
            tempUserSession.CultureInfo = GetUserCultureInfo();
            tempUserSession.UserIPAddress = GetUserIPAddress();
            tempUserSession.UserBrowser = HttpContext.Current.Request.Browser.Browser;
            tempUserSession.CurrentUser = lUser;

            Session["UserContext"] = tempUserSession;
       }

        private string GetUserIPAddress()
        {
            //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
            //client connecting to a web server through an HTTP proxy or load balancer
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
            }
            return ip;
        }
        private string GetUserCultureInfo()
        {
            //Currently we are treating all user with same cultural info. We will change ir based of user session.
            AppSettingsReader _AppSettingsReader = new AppSettingsReader();
            string _CultureInfo = _AppSettingsReader.GetValue(constCultureInfo, typeof(string)).ToString();
            return _CultureInfo;
        }
        #endregion Private Methods
    }
}